#!/usr/bin/env python
# coding: utf-8

import json
import os
import dashscope
from dashscope.api_entities.dashscope_response import Role
from flask import Flask, request, jsonify
from flask_cors import CORS

# 从环境变量中，获取 DASHSCOPE_API_KEY
api_key = os.environ.get("DASHSCOPE_API_KEY")
dashscope.api_key = api_key


# 封装模型响应函数
def get_response(messages):
    response = dashscope.Generation.call(
        model="qwen-turbo",
        messages=messages,
        result_format="message",  # 将输出设置为message形式
    )
    return response


app = Flask(__name__)
CORS(app)


# 读取 system prompt 文件内容
def load_system_prompt():
    with open("sec0721/system_prompt.md", "r", encoding="utf-8") as f:
        return f.read()


@app.route("/ai/secretary/get-response", methods=["POST"])
def api_get_response():
    data = request.get_json()
    messages = data.get("messages")
    review = data.get("review")

    if messages:
        # 多轮对话，直接用传入的 messages
        pass
    elif review:
        # 单轮对话，兼容原有逻辑
        system_prompt = load_system_prompt()  # 读取专业 prompt
        messages = [
            {
                "role": "system",
                "content": system_prompt,
            },
            {"role": "user", "content": review},
        ]
    else:
        return jsonify({"error": "Missing review or messages parameter"}), 400

    response = get_response(messages)
    content = response.output.choices[0].message.content
    return jsonify({"code": 0, "data": content})


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)
